from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import sys
import time
import multiprocessing

from .mapp2 import Ui_RAMCPUUSAGE
from .app2 import *


# 新的线程：创建一个信号，该信号每隔2s发送一次
# 线程启动后会自动开始执行run()函数
class Worker(QThread):
    sinOut = pyqtSignal(str, str)    # 创建一个信号，信号必须在类创建时定义，不能在类创建后作为类的属性动态添加进来

    def __init__(self, parent=None):
        super(Worker, self).__init__(parent)
        self.working = True
        self.num = 0

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):
        while self.working is True:
            memory = getMemory()
            cpu = getCpu()
            self.num += 1
            # 发射信号
            self.sinOut.emit(cpu, memory)
            # 线程休眠2秒
            self.sleep(1)


class mapp2MWin(QWidget, Ui_RAMCPUUSAGE):
    def __init__(self, parent=None):
        super(mapp2MWin, self).__init__(parent)
        self.setupUi(self)
        # 获取列表
        # self.initFileMemu()
        self.thread = Worker()
        self.thread.sinOut.connect(self.getDataRefash)        # 将信号连接到slotAdd，信号由线程每隔2s发送一次
        self.thread.start()

    def initFileMemu(self):
        print("mapp2MWin")
        # 获取列表
        # self.p = multiprocessing.Process(target=self.getDataRefash)
        # self.p.start()
        # self.p = QThread(self.getDataRefash)
        # self.p.start()
        self.timer = QTimer()
        self.timer.timeout.connect(self.getDataRefash)

        self.timer.start(5)
        pass

    def getDataRefash(self, cpu, memory):
        # while True:
        # print("getDataRefash")
        # memory = getMemory()
        # cpu = getCpu()
        self.label_5.setText(cpu)
        self.label_12.setText(memory)
        # print("CPU占用：%s \t 内存占用：%s" % (cpu, memory))
        # time.sleep(0.2)



    def error_handler(self, emsg):
        print(emsg)
        QMessageBox.warning(self, "error_handler", emsg, QMessageBox.Ok)



    def custonSlots(self):
        print("custonSlots")
        pass




if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = mapp2MWin()
    w.show()
    sys.exit(app.exec_())

